package com.tian.config;

import com.tian.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * {@code @description:} 安全校验
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-27 10:10
 * {@code @version:} 1.0
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserService userService;

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {

        return super.authenticationManager();
    }

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                /*.passwordEncoder(new PasswordEncoder() {
                    @Override
                    public String encode(CharSequence charSequence) {
                        return passwordEncoder().encode(charSequence);
                    }

                    @Override
                    public boolean matches(CharSequence charSequence, String s) {
                        return passwordEncoder().matches(charSequence, s);
                    }
                })*/;
    }

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/swagger").antMatchers("/regitser")
                .antMatchers("/document-*");
        //放Gateway里写
//        web.addSecurityFilterChainBuilder(null);
//        web.expressionHandler()
    }

    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and()
                .httpBasic()
                .and().cors()
                .and().csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        //对密码加密
        return new BCryptPasswordEncoder();
    }
}
